<template>
    <div class="admin-content">
        <!-- 主要内容区域 -->
        <div class="main-content">
            <div class="content-card">
                <div class="card-header">
                    <el-icon class="header-icon">
                        <Setting />
                    </el-icon>
                    <h2>管理员工作台</h2>
                </div>

                <!-- 订单管理表格 -->
                <div class="order-table-section">
                    <SmartTable :columns="orderColumns" :data="displayOrders" :loading="ordersLoading" :border="true"
                        :stripe="true" :show-pagination="false" />
                </div>

                <!-- 统计卡片 -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <Calendar />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ todayStats.totalOrders }}</div>
                            <div class="stat-label">今日订单</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <DataAnalysis />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ totalStats.totalOrders }}</div>
                            <div class="stat-label">总订单数</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <Location />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ mostPopularPickup.name }}</div>
                            <div class="stat-label">最多取货点</div>
                            <div class="stat-sublabel">{{ mostPopularPickup.count }}单</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <House />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ mostPopularDelivery.name }}</div>
                            <div class="stat-label">最多收货点</div>
                            <div class="stat-sublabel">{{ mostPopularDelivery.count }}单</div>
                        </div>
                    </div>
                </div>

                <!-- 地图区域 -->
                <div class="map-section">
                    <h3>校园配送订单分布图</h3>
                    <div class="map-container">
                        <ChinaMap :title="'校园配送订单分布图'" :map-name="'ahute'" :data="mapData" :height="500" :theme="'blue'"
                            :show-legend="true" :enable-zoom="true" :show-boundary="true" :show-labels="true" />
                    </div>
                </div>

                <!-- 详细统计表格（改用 SmartTable） -->
                <div class="table-section">
                    <div class="section-header">
                        <h3>各宿舍楼订单统计</h3>
                        <div class="table-controls">
                            <el-button size="small" @click="refreshData">
                                <el-icon>
                                    <Refresh />
                                </el-icon>
                                刷新数据
                            </el-button>
                        </div>
                    </div>

                    <SmartTable :columns="dormColumns" :data="displayDormitoryStats" :loading="false" :border="true"
                        :stripe="true" :show-pagination="false" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Calendar, DataAnalysis, Location, House, Refresh, Setting } from '@element-plus/icons-vue'
import ChinaMap from '@/components/charts/ChinaMap.vue'
import SmartTable from '@/components/smart-table/SmartTable.vue'
import { getAdminStats, getLocationList, getAdminDeliveryOrders } from '@/api/delivery'
import { formatTimestamp } from '@/utils/date'

// 统计数据
const todayStats = reactive({
    totalOrders: 0,
    completedOrders: 0,
    pendingOrders: 0
})

const totalStats = reactive({
    totalOrders: 0,
    completedOrders: 0,
    pendingOrders: 0
})

// 最多取货点和收货点
const mostPopularPickup = reactive({
    name: '暂无数据',
    count: 0
})

const mostPopularDelivery = reactive({
    name: '暂无数据',
    count: 0
})

// 地点数据
const locationData = ref<any[]>([])

// 取货点选项
const pickupPoints = computed(() => {
    return locationData.value
        .filter(location => location.isPickupPoint)
        .map(location => ({
            value: location.locationId,
            label: location.name
        }))
})

// 送货点选项
const deliveryPoints = computed(() => {
    return locationData.value.map(location => ({
        value: location.locationId,
        label: location.name
    }))
})

// 宿舍楼统计数据（与ahute.json中的实际数据匹配）
const dormitoryStats = ref([
    {
        name: 'G1栋',
        todayOrders: 8,
        totalOrders: 98,
        pickupOrders: 5,
        deliveryOrders: 3,
        completionRate: 92
    },
    {
        name: 'G2栋',
        todayOrders: 14,
        totalOrders: 167,
        pickupOrders: 9,
        deliveryOrders: 5,
        completionRate: 89
    },
    {
        name: 'G3栋',
        todayOrders: 12,
        totalOrders: 156,
        pickupOrders: 8,
        deliveryOrders: 4,
        completionRate: 95
    },
    {
        name: 'G4栋',
        todayOrders: 18,
        totalOrders: 203,
        pickupOrders: 12,
        deliveryOrders: 6,
        completionRate: 92
    },
    {
        name: '4栋',
        todayOrders: 15,
        totalOrders: 189,
        pickupOrders: 10,
        deliveryOrders: 5,
        completionRate: 88
    },
    {
        name: '6栋',
        todayOrders: 22,
        totalOrders: 267,
        pickupOrders: 15,
        deliveryOrders: 7,
        completionRate: 96
    },
    {
        name: '7栋',
        todayOrders: 9,
        totalOrders: 134,
        pickupOrders: 6,
        deliveryOrders: 3,
        completionRate: 90
    }
])

// SmartTable 列定义
const dormColumns = [
    { key: 'name', label: '宿舍楼', width: 120 },
    { key: 'todayOrders', label: '今日订单', width: 100, align: 'center', type: 'string' },
    { key: 'totalOrders', label: '总订单', width: 100, align: 'center', type: 'string' },
    { key: 'pickupOrders', label: '取货订单', width: 100, align: 'center', type: 'string' },
    { key: 'deliveryOrders', label: '收货订单', width: 100, align: 'center', type: 'string' },
    {
        key: 'completionRate', label: '完成率', width: 140, align: 'center', type: 'string',
        render: (row: any) => `<div style="display:flex;align-items:center;gap:6px;justify-content:center"><div class='el-progress el-progress--line' style='width:80px'><div class='el-progress-bar'><div class='el-progress-bar__outer' style='height:8px'><div class='el-progress-bar__inner' style='width:${row.completionRate}%;'></div></div></div></div><span style='font-size:12px;color:#666'>${row.completionRate}%</span></div>`
    },
]

// 当后端无数据时显示默认数据
const defaultDormitoryStats = [
    { name: 'G1栋', todayOrders: 0, totalOrders: 0, pickupOrders: 0, deliveryOrders: 0, completionRate: 0 },
    { name: 'G2栋', todayOrders: 0, totalOrders: 0, pickupOrders: 0, deliveryOrders: 0, completionRate: 0 },
]

const displayDormitoryStats = computed(() => {
    return Array.isArray(dormitoryStats.value) && dormitoryStats.value.length > 0
        ? dormitoryStats.value
        : defaultDormitoryStats
})

// 地图数据
const mapData = computed(() => {
    const data = dormitoryStats.value.map(dorm => {
        // 处理不同的宿舍楼名称格式
        let geoJsonName = dorm.name
        if (dorm.name.includes('G') && dorm.name.includes('栋')) {
            // G1栋 -> G1
            geoJsonName = dorm.name.replace('栋', '')
        } else if (dorm.name.includes('栋') && !dorm.name.includes('G')) {
            // 4栋 -> 4栋 (保持不变)
            geoJsonName = dorm.name
        }

        return {
            name: geoJsonName,
            value: dorm.totalOrders,
            description: `总订单: ${dorm.totalOrders}单`,
            unit: '单'
        }
    })

    console.log('地图数据:', data)
    return data
})

const formatDate = (ts: number | string | Date | null | undefined) => formatTimestamp(ts)

// 订单表 SmartTable 配置与数据
const ordersLoading = ref(false)
const orderColumns = [
    { key: 'orderId', label: '订单号', width: 140, align: 'center', type: 'string', filterable: true },
    { key: 'recipientName', label: '收件人', width: 100, align: 'center', type: 'string', filterable: true },
    { key: 'phone', label: '联系电话', width: 120, align: 'center', type: 'string' },
    { key: 'pickup', label: '取货点', width: 120, type: 'string', filterable: true },
    { key: 'delivery', label: '送达点', width: 120, type: 'string', filterable: true },
    {
        key: 'status', label: '状态', width: 100, type: 'tag', filterable: true,
        tagConfig: { typeMap: { '待取件': 'warning', '配送中': 'primary', '已送达': 'success' } }, align: 'center'
    },
    { key: 'createdAt', label: '创建时间', width: 160, align: 'center', type: 'datetime', filterable: true },
]

// 后端返回列表
const orders = ref<any[]>([])

// 默认展示数据
const defaultOrders = [
    { orderId: 'MOCK-20250906-001', recipientName: '张三', phone: '13170080209', pickup: '阶教103', delivery: 'G3栋5楼518', status: '已送达', createdAt: '2025-09-06 16:11:16' },
    { orderId: 'MOCK-20250906-002', recipientName: '李四', phone: '13900001111', pickup: '徽润超市', delivery: 'G4栋3楼302', status: '配送中', createdAt: '2025-09-06 16:20:03' },
]

// 展示数据（空则回退默认）
const displayOrders = computed(() => (orders.value && orders.value.length ? orders.value : defaultOrders))

// 拉取订单数据：失败或返回空数组时，使用默认数据
const fetchOrders = async () => {
    ordersLoading.value = true
    try {
        const res = await getAdminDeliveryOrders({ page: 1, pageSize: 20 })
        if (res && Array.isArray(res)) {
            orders.value = res.map(o => ({
                orderId: o.id,
                recipientId: o.requesterId,
                recipientName: o.requesterName,
                phone: o.requesterPhone,
                pickup: o.pickupDetails || o.pickupAddress,
                delivery: o.deliverDetails || o.deliveryAddress,
                status: o.status === 'delivered' ? '已送达' : (o.status === 'in_progress' ? '配送中' : '待取件'),
                createdAt: formatDate(o.createTime),
            }))
        } else {
            orders.value = [] // 触发回退默认
        }
    } catch (e) {
        console.error('获取订单列表失败:', e)
        orders.value = [] // 回退默认
    } finally {
        ordersLoading.value = false
    }
}

// 获取地点数据
const fetchLocationData = async () => {
    try {
        const response = await getLocationList()
        if (response && Array.isArray(response)) {
            locationData.value = response
        } else {
            // 使用默认地点数据
            locationData.value = [
                { locationId: 'jeijiao103', name: '阶教103', isPickupPoint: true },
                { locationId: 'huirunchaoshi', name: '徽润超市', isPickupPoint: true },
                { locationId: 'g3dong', name: 'G3栋', isPickupPoint: false },
                { locationId: 'g4dong', name: 'G4栋', isPickupPoint: false },
                { locationId: 'g5dong', name: 'G5栋', isPickupPoint: false }
            ]
        }
    } catch (error) {
        console.error('获取地点数据失败:', error)
        // 使用默认地点数据
        locationData.value = [
            { locationId: 'jeijiao103', name: '阶教103', isPickupPoint: true },
            { locationId: 'huirunchaoshi', name: '徽润超市', isPickupPoint: true },
            { locationId: 'g3dong', name: 'G3栋', isPickupPoint: false },
            { locationId: 'g4dong', name: 'G4栋', isPickupPoint: false },
            { locationId: 'g5dong', name: 'G5栋', isPickupPoint: false }
        ]
    }
}

// 获取管理员统计数据
const fetchAdminStats = async () => {
    try {
        const response = await getAdminStats()
        if (response) {
            // 更新统计数据
            Object.assign(todayStats, response.todayStats || {})
            Object.assign(totalStats, response.totalStats || {})
            Object.assign(mostPopularPickup, response.mostPopularPickup || {})
            Object.assign(mostPopularDelivery, response.mostPopularDelivery || {})

            // 更新宿舍楼统计
            if (response.dormitoryStats) {
                dormitoryStats.value = response.dormitoryStats
            }
        }
    } catch (error) {
        console.error('获取管理员统计数据失败:', error)
        // 使用默认数据
    }
}

// 刷新数据
const refreshData = async () => {
    await fetchAdminStats()
}

// 组件挂载时获取数据
onMounted(async () => {
    await fetchLocationData()
    await fetchAdminStats()
    await fetchOrders()
})
</script>

<style scoped>
.admin-content {
    padding: 20px;
}

.main-content {
    display: flex;
    justify-content: center;
    max-width: 1400px;
    margin: 0 auto;
}

.content-card {
    background: white;
    border-radius: 16px;
    padding: 30px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    width: 100%;
    max-width: 1200px;
}

.card-header {
    display: flex;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 2px solid #f0f0f0;
}

.header-icon {
    font-size: 1.5rem;
    color: #3498db;
    margin-right: 12px;
}

.card-header h2 {
    margin: 0;
    font-size: 1.5rem;
    color: #333;
    font-weight: 600;
}

.order-table-section {
    margin-bottom: 30px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: linear-gradient(135deg, #f8f9ff 0%, #e8f0ff 100%);
    border-radius: 12px;
    padding: 20px;
    display: flex;
    align-items: center;
    border: 1px solid #e0e7ff;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    background: #3498db;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
}

.stat-icon .el-icon {
    font-size: 1.5rem;
    color: white;
}

.stat-content {
    flex: 1;
}

.stat-number {
    font-size: 1.5rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 4px;
    line-height: 1;
}

.stat-label {
    font-size: 0.9rem;
    color: #666;
    margin-bottom: 2px;
}

.stat-sublabel {
    font-size: 0.8rem;
    color: #999;
}

.map-section {
    margin-bottom: 30px;
}

.map-section h3 {
    margin: 0 0 20px 0;
    font-size: 1.3rem;
    color: #333;
    font-weight: 600;
}

.map-container {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-section {
    background: #fafafa;
    border-radius: 12px;
    padding: 24px;
    border: 1px solid #e0e0e0;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e9ecef;
}

.section-header h3 {
    margin: 0;
    font-size: 1.3rem;
    color: #333;
    font-weight: 600;
}

.table-controls {
    display: flex;
    gap: 8px;
}

.progress-text {
    font-size: 12px;
    color: #666;
    margin-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .admin-content {
        padding: 16px;
    }

    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
    }

    .stat-card {
        padding: 16px;
    }

    .stat-number {
        font-size: 1.3rem;
    }

    .section-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }

    .table-controls {
        width: 100%;
        justify-content: flex-end;
    }
}

@media (max-width: 480px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }

    .stat-card {
        flex-direction: column;
        text-align: center;
        gap: 12px;
    }

    .stat-icon {
        width: 40px;
        height: 40px;
        margin-right: 0;
    }

    .stat-icon .el-icon {
        font-size: 1.2rem;
    }

    .stat-number {
        font-size: 1.2rem;
    }
}
</style>